package com.metacube.metaconnect.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LikeDAO {

	private Connection conn;

	public LikeDAO() {
		conn = CreateConnectionToDatabase.createConnection();
	}

	/**
	 * 
	 * @param email
	 *            email_id of the person who likes the comment
	 * @param post_id
	 *            post_id on which comment liked
	 * @return true if like is successfully posted else return false
	 */
	public boolean insertLike(String email, int post_id) {
		String query = "insert into likes values(?,?)";

		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(query);

			ps.setInt(1, post_id);
			ps.setString(2, email);

			int result = ps.executeUpdate();

			if (result == 1)
				return true;
		} catch (SQLException e) {

		}
		return false;
	}

	/**
	 * counts number of likes on a post
	 * 
	 * @param post_id
	 *            post_id of the post
	 * @return number of likes on a post
	 */
	public String countLike(String post_id) {

		int pid = Integer.parseInt(post_id);

		String query = "select count(*) from likes where post_id =?";

		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(query);

			ps.setInt(1, pid);

			ResultSet rs = ps.executeQuery();

			if (rs.next()) {
				return rs.getString(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * checks whether user likes a post or not
	 * 
	 * @param post_id
	 *            post_id of a post
	 * @param email
	 *            email_id of the user
	 * @return true if user likes the post else return false
	 */
	public boolean checkIfLike(String post_id, String email) {
		String query = "Select * from likes where post_id =? and email_id_who_likes =?";

		PreparedStatement ps = null;

		int pid = Integer.parseInt(post_id);
		try {

			ps = conn.prepareStatement(query);

			ps.setInt(1, pid);
			ps.setString(2, email);

			ResultSet rs = ps.executeQuery();

			if (rs.next()) {
				return true;
			}
		} catch (SQLException e) {

		}
		return false;
	}
}
